from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework import serializers
from rest_framework.decorators import action
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from goods.models import SPU, GoodsCategory, Brand
from meiduo_admin.serializers.spus import SPUSpecificationSerializer, BrandSerializer, CategorySerializer
from meiduo_admin.utils import PageNum


class SPUView(ModelViewSet):
    serializer_class = SPUSpecificationSerializer
    queryset = SPU.objects.all()
    pagination_class = PageNum
    permission_classes = [IsAdminUser]


    def simple(self,request):
        data = Brand.objects.all()
        ser = BrandSerializer(data,many=True)
        return Response(ser.data)


    def channel(self,request):
        data = GoodsCategory.objects.filter(parent = None)
        ser = CategorySerializer(data,many=True)
        return Response(ser.data)

    def channels(self,request,pk):
        data = GoodsCategory.objects.filter(parent_id = pk)
        ser = CategorySerializer(data,many=True)
        return Response(ser.data)


    def image(self,request):
        #建立fastdfs
        client = Fdfs_client(settings.FASTDFS_PATH)
        file = request.FILES.get('image')

        #上传图片
        res = client.upload_by_buffer(file.read())
        # 判断是否上传成功
        if res['Status'] != 'Upload successed.':
            raise serializers.ValidationError({'error':'图片上传失败'})
        #保存图片表
        image_url = res['Remote file_id']
        return Response(
         { 'image_url':settings.FASTDFS_PATH+image_url},
            status=201
        )











